<script lang="ts" setup>
import { onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';

import { LOGIN_PATH } from '@vben/constants';
import { useAccessStore, useUserStore } from '@vben/stores';

import { message } from 'ant-design-vue';

import { getUserInfoApi, loginByToken } from '#/api';
import { auto1688stor } from '#/store';

const route = useRoute();
const token = route.query.token;

const accessStore = useAccessStore();
const userStore = useUserStore();
const router = useRouter();

onMounted(() => {
  if (token !== null && token !== 'null' && token !== '') {
    // message.error(token);
    loginByTokenApi();
  } else {
    message.error('code错误');
    router.push(LOGIN_PATH);
  }
});

function loginByTokenApi() {
  const data = { token };

  loginByToken(data).then((res: any) => {
    const accessToken = res.access_token;
    const refreshToken = res.refresh_token;
    accessStore.setRefreshToken(refreshToken);
    accessStore.setAccessToken(accessToken);

    fetchUserInfo(res.user_id);
  });
}
function fetchUserInfo(user_id: any) {
  getUserInfoApi().then(async (res) => {
    const userInfo = res;
    // console.log(userInfo);
    userInfo.username = userInfo.user.userName;
    userInfo.userId = userInfo.user.userId;
    userInfo.phonenumber = userInfo.user.phonenumber;
    userInfo.realName = userInfo.user.userName;
    userStore.setUserInfo(userInfo);
    const auto1688 = auto1688stor();
    await auto1688.auto1688BindShop(user_id);

    router.push('/shop-order/up-shop-orders');
  });
}
</script>
